package nickname;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class GetInfo extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private final Logger logger = Logger.getLogger(GetInfo.class);
	private static String cache = null;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.debug(Utils.request2NiceString(req));
		PrintWriter writer = resp.getWriter();
		String ggId = req.getParameter("ggid");
		String responseText = null;
		try {
			logger.debug("Getting info for gg number: " + ggId);
			responseText = getInfoFromOfficialServer(ggId);
		} catch (IOException e) {
			logger.warn("I/O Error while getting info from official server, offering default response");
			responseText = getDefaultInfoResponse();
		}

		resp.setContentType("text/html");
		writer.write(responseText);
		logger.debug("Response " + new String(responseText));
		writer.close();
	}

	private String getDefaultInfoResponse() throws IOException, FileNotFoundException {
		if (cache == null) {
			InputStream defaultResponseFromFile = getClass().getResourceAsStream("/inforesponse.txt");
			cache = Utils.inputStream2String(defaultResponseFromFile);
		}
		return cache;
	}

	private String getInfoFromOfficialServer(String ggId) throws IOException {
		URL url = new URL("http://" + Config.MOBILE_GADUGADU_SERVER_HOST + "/web/getinfo.php?ggid=" + ggId
				+ "&type=mgg&ver=mgg1.4.1/android&sizex=320&sizey=533");
		HttpURLConnection urlc = HttpConnectionFactory.createHttpConnection(url);
		return Utils.inputStream2String(urlc.getInputStream());
	}
}
